package com.kinon.ogt.utils;

import com.kinon.ogt.api.exception.ApiException;
import com.kinon.ogt.model.BaseResponse;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * 佛祖保佑 永无BUG
 *
 * @author WangZhiYao
 * @date 2018/4/23
 */
public class RxUtils {

    public static <T> FlowableTransformer<T, T> rxSchedulerHelper() {
        return observable -> observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public static <T> FlowableTransformer<BaseResponse<T>, T> handleResult() {
        return upstream -> upstream.flatMap((Function<BaseResponse<T>, Flowable<T>>) tBaseResponse -> {
            if (tBaseResponse.isCode()) {
                return createData(tBaseResponse.getData());
            }
            return Flowable.error(new ApiException(tBaseResponse.getMsg()));
        });
    }

    public static <T> Flowable<T> createData(final T t) {
        return Flowable.create(emitter -> {
            try {
                emitter.onNext(t);
                emitter.onComplete();
            } catch (Exception e) {
                emitter.onError(e);
            }
        }, BackpressureStrategy.BUFFER);
    }
}
